package com.xyz.admin.modules.demo.controller;



import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xyz.admin.common.utils.Rest;
import com.xyz.admin.modules.demo.entity.DemoUser;
import com.xyz.admin.modules.demo.service.DemoUserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Random;


@Api(tags = "Demo")
@RequestMapping(value = "/api")
@RestController
public class DemoUserController {

    private static final Random RANDOM = new Random();


    @Autowired
    private DemoUserService userService;

    /**
     * 动态数据源的主库
     *
     * @return
     */
    @GetMapping("master")
    public List<DemoUser> master() {
        return userService.selectUsersFromMaster();
    }


    /**
     * 动态数据源代理的sharding-jdbc的从库,经过两次选择
     * 第一次:  dynamic-ds => sharding-ds
     * 第二次:  sharding-ds => slave
     *
     * @return
     */
    @GetMapping("shardingSlave")
    public List<DemoUser> shardingSlave() {
        return userService.selectUsersFromShardingSlave();
    }

    /**
     * 动态数据源代理的sharding-jdbc的主库,经过两次选择
     * 第一次:  dynamic-ds => sharding-ds
     * 第二次:  sharding-ds => master
     *
     * @return
     */
    @PostMapping("addUser")
    public DemoUser addUser() {
        DemoUser user = new DemoUser();
        user.setName("测试用户" + RANDOM.nextInt());
        user.setAge(RANDOM.nextInt(100));
        userService.addUser(user);
        return user;
    }

    /**
     * 动态数据源代理的sharding-jdbc的主库,经过两次选择
     * 第一次:  dynamic-ds => sharding-ds
     * 第二次:  sharding-ds => master
     *
     * @return
     */
    @DeleteMapping("sharding/{id}")
    public String deleteUser(@PathVariable Long id) {
        userService.deleteUserById(id);
        return "成功删除用户" + id;
    }


    @GetMapping("testmybatisplus")
    public Rest<DemoUser> testmybatisplus() {
        IPage<DemoUser> demoUsers = userService.testMyBatisPlusFun();

        return Rest.ok(demoUsers);
    }
}
